using UnityEngine;
using UnityEngine.Events;

namespace WorkFlow.TweenGo
{
    public sealed class TweenGoGroup : MonoBehaviour ,ITweenGoControl
    {
        [SerializeField] private TweenStart tweenStart;
        
        [SerializeField] private UnityEvent onPlay = new UnityEvent();
        public UnityEvent OnPlay => onPlay;
        [SerializeField] private UnityEvent onClear = new UnityEvent();
        public UnityEvent OnClear => onClear;
        
        private ITweenGoControl[] _tweenGoControls;
        private void Awake()
        {
            _tweenGoControls = gameObject.GetComponentsInChildren<ITweenGoControl>();
            if (tweenStart == TweenStart.OnAwake)
            {
                PlayGroupTween();
            }
        }


        void PlayGroupTween()
        {
            if (_tweenGoControls != null)
            {
                foreach (var tween in _tweenGoControls)
                {
                    if (tween is { StartTime: TweenStart.None } && tween != (ITweenGoControl)this)
                    {
                        tween.Play();
                    }
                }
            }
        }

        public TweenStart StartTime => tweenStart;
        public void Play()
        {
            onPlay?.Invoke();
            PlayGroupTween();
        }

        public void Clear()
        {
            onClear?.Invoke();
            if (_tweenGoControls != null)
            {
                foreach (var tween in _tweenGoControls)
                {
                    if (tween is { StartTime: TweenStart.None } && (TweenGoGroup)tween != this)
                    {
                        tween.Clear();
                    }
                }
            }
        }
    }
}
